from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange

def softmax_loss_naive(W, X, y, reg):
    """
    Softmax loss function, naive implementation (with loops)

    Inputs have dimension D, there are C classes, and we operate on minibatches
    of N examples.

    Inputs:
    - W: A numpy array of shape (D, C) containing weights.
    - X: A numpy array of shape (N, D) containing a minibatch of data.
    - y: A numpy array of shape (N,) containing training labels; y[i] = c means
      that X[i] has label c, where 0 <= c < C.
    - reg: (float) regularization strength

    Returns a tuple of:
    - loss as single float
    - gradient with respect to weights W; an array of same shape as W
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using explicit loops.     #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    num_train=X.shape[0]
    num_class=W.shape[1] 
    y_pred=np.dot(X,W)
    y_pred=y_pred-y_pred.max(axis=1).reshape(num_train,1)#减去最大值防止指数爆炸
 
    for i in xrange(num_train):
      e1=np.sum(np.exp(y_pred[i]))
      e2=np.exp(y_pred[i][y[i]])
      loss-=np.log(e2/e1)
      dW[:, y[i]] -= X[i]
      for j in xrange(num_class):
          dW[:, j] += np.exp(y_pred[i][j]) / e1 * X[i]
    pass
    loss=loss/num_train+0.5*reg*np.sum(W*W)#正则化
    dW=dW/num_train+reg*W

    
    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    return loss, dW


def softmax_loss_vectorized(W, X, y, reg):
    """
    Softmax loss function, vectorized version.

    Inputs and outputs are the same as softmax_loss_naive.
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    num_train=X.shape[0]
    num_class=W.shape[1] 
    y_pred=np.dot(X,W)#N*C
    y_pred=y_pred-y_pred.max(axis=1).reshape(-1,1)#减去最大值防止指数爆炸
    softmax_output = np.exp(y_pred)/\
    np.sum(np.exp(y_pred), axis = 1).reshape(-1,1)#N*C
    loss=-np.sum(np.log(softmax_output[range(num_train),list(y)]))
    loss/=num_train
    loss+=0.5*reg*np.sum(W*W);

    softmax_output[range(num_train),list(y)]+=-1
    dW=(X.T).dot(softmax_output)
    dW=dW/num_train+reg*W
    pass

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    return loss, dW
